package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.beans.WeiXinPayBean;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class PayActivity extends BaseActivity implements View.OnClickListener{
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_complete;
    //选中支付
    private LinearLayout ll_root_pay;


    private LinearLayout ll_sure;
    private ImageView iv_sure;
    private TextView tv_pay;
    private PopupWindow popFail;


    private boolean isSure = false;

    private IWXAPI api;

    private TextView tv_price;
    private TextView tv_count;
    private String price;
    private String count;
    private String out_trade_no;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        sp = getSharedPreferences("paynumber",MODE_PRIVATE);
        editor = sp.edit();
        Intent intent = getIntent();

        if (intent.hasExtra("price")){
            price = intent.getStringExtra("price");
           // Log.i("data--data--price-->","price:"+price+" count:"+count);
        }
        if (intent.hasExtra("count")){
            count = intent.getStringExtra("count");
        }
       // Log.i("data--data---->","price:"+price+" count:"+count);
        initView();
        initData();
        initListener();


    }

    @Override
    protected void updateByHandler(Message msg) {

        switch (msg.what){
            case MessageCode.NETWORKCODE_WEIXINPAY_SUCCESS:
                WeiXinPayBean weiXinPayBean = (WeiXinPayBean) msg.obj;
                api = WXAPIFactory.createWXAPI(mContext, weiXinPayBean.getAppid(),false);
                api.registerApp(weiXinPayBean.getAppid());
                out_trade_no = weiXinPayBean.getOut_trade_no();
                if (!TextUtils.isEmpty(out_trade_no)){
                    editor.putString("out_trade_no",out_trade_no);
//                    editor.putString("out_trade_no","TNO2017042421563948400000001");
                    editor.commit();
                }
             //   Log.i("--out_trade_no->",weiXinPayBean.getOut_trade_no());
                PayReq req = new PayReq();
                req.appId			= "wx9ce43769100c2cc1";
                req.partnerId		= weiXinPayBean.getPartnerid();
                req.prepayId		= weiXinPayBean.getPrepayid();
                req.nonceStr		= weiXinPayBean.getNoncestr();
                req.timeStamp		= weiXinPayBean.getTimestamp();
                req.packageValue	= "Sign=WXPay";
                req.sign			= weiXinPayBean.getSign();
//                req.extData			= ((System.currentTimeMillis()+300) /1000 ) +""; // optional
              //  Log.i("--weixinPay->",weiXinPayBean.toString());
                api.sendReq(req);
                tv_pay.setEnabled(true);
                break;
            case MessageCode.NETWORKCODE_WEIXINPAY_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datagetfail);
                }
                break;

        }
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_complete = (TextView) findViewById(R.id.tv_title_func);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText("购买");

        ll_sure = (LinearLayout) findViewById(R.id.pay_sure_linear);
        iv_sure = (ImageView) findViewById(R.id.pay_sure_iv);

        tv_pay = (TextView) findViewById(R.id.pay_consult_ask);
        ll_root_pay = (LinearLayout) findViewById(R.id.activity_pay);

        tv_price = (TextView) findViewById(R.id.pay_text_money);
        tv_count = (TextView) findViewById(R.id.pay_text_count);
    }

    @Override
    protected void initListener() {
        ll_sure.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        tv_pay.setOnClickListener(this);
    }

    @Override
    protected void initData() {

        if (!TextUtils.isEmpty(count)){
            tv_count.setText("图文咨询"+count+"次");
        }
        if (!TextUtils.isEmpty(price)){
            tv_price.setText(price);
        }


    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if(intent.getStringExtra("codes") != null)
        {
            if(intent.getStringExtra("codes").equals("-1"))
            {
                showFailPop();
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.pay_sure_linear:
                if (!isSure){
                    isSure = true;
                    iv_sure.setImageResource(R.drawable.pay_sure);
                }else {
                    isSure = false;
                    iv_sure.setImageResource(R.drawable.pay_sure_back);
                }
                break;
            case R.id.pay_consult_ask:
                if (isSure){
                    Log.i("YiJiaHuNetWorkUtils","loginInfo.getUserId() = "+loginInfo.getUserId()+"price = "+ price);
//                    医生在线咨询服务包

                        YiJiaHuNetWorkUtils.weiXinPay(loginInfo.getUserId(),"001",price,"DoctorOnlineServicePackage",handler);
                        tv_pay.setEnabled(false);
                  //  showFailPop();
                }else {
                    toastMsg("请选中支付");
                }
                break;

        }
    }

    private void showFailPop() {

        View views = LayoutInflater.from(PayActivity.this).inflate(R.layout.popwinds_payactivity_fail,null);
        TextView tv_pay = (TextView) views.findViewById(R.id.popwinds_pay_fail);
        tv_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popFail.dismiss();
            }
        });
        popFail = new PopupWindow(views, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popFail.setFocusable(true);
        popFail.setOutsideTouchable(true);
        popFail.setTouchable(true);
        popFail.setBackgroundDrawable(new BitmapDrawable());
//        popFail.showAtLocation(ll_root_pay, Gravity.CENTER,0,0);
        popFail.showAtLocation(ll_title, Gravity.CENTER,0,0);
    }
}
